package us.luosl.lslt.asyn.trigger;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 根据定长时间，和数据条数来判断是否触发的简单 Trigger
 */
public class TimeAndCountTrigger<T> implements Trigger<T> {

    /**
     * 纳秒和毫秒的进制
     */
    private static final int NANOS_SCALE = 1000000;

    /**
     * collector size 阈值
     */
    private int threshold;

    /**
     * 刷新间隔 纳秒
     */
    private long flushDurationNanos;

    public TimeAndCountTrigger(int threshold, long flushDurations) {
        this.threshold = threshold;
        this.flushDurationNanos = flushDurations * NANOS_SCALE;
    }

    @Override
    public boolean isTrigger(LocalDateTime lastExecuteTime, List<T> collector) {
        Duration duration = Duration.between(lastExecuteTime, LocalDateTime.now());
        boolean hasData = collector.size() > 0;
        boolean flushDurationOk = duration.toNanos() >= flushDurationNanos;
        boolean thresholdOk = collector.size() >= threshold;
        return hasData && (flushDurationOk || thresholdOk);
    }
}
